<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blogwebpage/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blogwebpage/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/blogwebpage/images/favicon.ico">
  <link rel="mask-icon" href="/blogwebpage/images/logo.svg" color="#222">
  <meta name="msvalidate.01" content="9BDlx6FiNE">

<link rel="stylesheet" href="/blogwebpage/css/main.css">


<link rel="stylesheet" href="/blogwebpage/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangkejie.gitee.io","root":"/blogwebpage/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Hybrid为什么需要这种设计，或者技术方案，我们就不多说了,但是我还是要强调几点个人的见解  最好不要大面积使用此方案，以免影响用户体验，最好别超过项目的30%。 在某些页面变化比较大，而又不太需要性能的页面，采取此设计非常合适 还有一个非常重要的，一定要注意，此交互方案在app内是异步线程，注意要回到主线程处理UI。安卓和iOS都是如此！！！  在安卓上面我们有三种方案，分别是   Nativ">
<meta property="og:type" content="article">
<meta property="og:title" content="Hybrid">
<meta property="og:url" content="https://wangkejie.gitee.io/blogwebpage/iOS/hybrid/hybrid.html">
<meta property="og:site_name" content="王科杰">
<meta property="og:description" content="Hybrid为什么需要这种设计，或者技术方案，我们就不多说了,但是我还是要强调几点个人的见解  最好不要大面积使用此方案，以免影响用户体验，最好别超过项目的30%。 在某些页面变化比较大，而又不太需要性能的页面，采取此设计非常合适 还有一个非常重要的，一定要注意，此交互方案在app内是异步线程，注意要回到主线程处理UI。安卓和iOS都是如此！！！  在安卓上面我们有三种方案，分别是   Nativ">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2015-12-30T16:00:00.000Z">
<meta property="article:modified_time" content="2021-06-25T08:55:53.143Z">
<meta property="article:author" content="Jack Wang">
<meta property="article:tag" content="Hybrid">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wangkejie.gitee.io/blogwebpage/iOS/hybrid/hybrid.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Hybrid | 王科杰</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?93e26277de0cf2c5851167f2c6dcaa7d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blogwebpage/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">王科杰</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Jack's Notes</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blogwebpage/" rel="section"><i class="home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blogwebpage/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">52</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blogwebpage/me/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blogwebpage/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">54</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blogwebpage/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">56</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/hybrid/hybrid.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Hybrid
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2015-12-31 00:00:00" itemprop="dateCreated datePublished" datetime="2015-12-31T00:00:00+08:00">2015-12-31</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/Hybrid/" itemprop="url" rel="index"><span itemprop="name">Hybrid</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="Hybrid"><a href="#Hybrid" class="headerlink" title="Hybrid"></a>Hybrid</h1><p>为什么需要这种设计，或者技术方案，我们就不多说了,但是我还是要强调几点个人的见解</p>
<ul>
<li>最好不要大面积使用此方案，以免影响用户体验，最好别超过项目的30%。</li>
<li>在某些页面变化比较大，而又不太需要性能的页面，采取此设计非常合适</li>
<li>还有一个非常重要的，一定要注意，此交互方案在app内是异步线程，注意要回到主线程处理UI。安卓和iOS都是如此！！！</li>
</ul>
<h2 id="在安卓上面"><a href="#在安卓上面" class="headerlink" title="在安卓上面"></a>在安卓上面</h2><p>我们有三种方案，分别是 </p>
<ol>
<li>Native提供方法，js调用Native方法</li>
<li>Native在本地注入js方法并且调用</li>
<li>Webview拦截Ajax请求，并做业务处理</li>
</ol>
<h2 id="Native提供方法，js调用Native方法"><a href="#Native提供方法，js调用Native方法" class="headerlink" title="Native提供方法，js调用Native方法"></a>Native提供方法，js调用Native方法</h2><ul>
<li>native注入对象（有一系列供js使用的方法）以及提供给js调用的名称。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">webView.addJavascriptInterface(<span class="keyword">new</span> HybridJsInterface(),<span class="string">&quot;HybridJSInterface&quot;</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li>native提供可以供js调用的方法。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HybridJsInterface</span> </span>&#123;</span><br><span class="line">    <span class="meta">@JavascriptInterface</span></span><br><span class="line">    <span class="function"><span class="keyword">final</span> <span class="keyword">public</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">(String text)</span></span></span><br><span class="line"><span class="function">    Log.<span class="title">i</span><span class="params">(<span class="string">&quot;method hello&quot;</span>,<span class="string">&quot;text=&quot;</span>+text)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>js调用native的方法。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">hybrid</span>(<span class="params"></span>)</span>&#123;    </span><br><span class="line">    <span class="built_in">window</span>.HybridJSInterface.hello(<span class="string">&quot;hello hybrid&quot;</span>); </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Native在本地注入js方法并且调用"><a href="#Native在本地注入js方法并且调用" class="headerlink" title="Native在本地注入js方法并且调用"></a>Native在本地注入js方法并且调用</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//    function helloJs()&#123;</span> </span><br><span class="line"><span class="comment">//        alert(&quot;hello js&quot;);</span> </span><br><span class="line"><span class="comment">//    &#125;</span></span><br><span class="line">String script = <span class="string">&quot;function helloJs()&#123; alert(&#x27;hello js&#x27;);&#125;&quot;</span>;</span><br><span class="line"><span class="comment">//script是js方法对应的字符串</span></span><br><span class="line"><span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.KITKAT) &#123;</span><br><span class="line">    mWebContent.evaluateJavascript(script, <span class="keyword">null</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    mWebContent.loadUrl(<span class="string">&quot;javascript:&quot;</span> + script);</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">String handle = <span class="string">&quot;helloJs()&quot;</span>;</span><br><span class="line">  <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.KITKAT) &#123;</span><br><span class="line">      mWebContent.evaluateJavascript(handle, <span class="keyword">null</span>);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      mWebContent.loadUrl(<span class="string">&quot;javascript:&quot;</span> + handle);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>


<h2 id="Webview拦截Ajax请求，并做业务处理"><a href="#Webview拦截Ajax请求，并做业务处理" class="headerlink" title="Webview拦截Ajax请求，并做业务处理"></a>Webview拦截Ajax请求，并做业务处理</h2><ol>
<li><p>native拦截h5发过来的请求协议（自定义协议）。<br>webview位置拦截的WebViewClient对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">webView.setWebViewClient(<span class="keyword">new</span> HybridWebViewClient());</span><br></pre></td></tr></table></figure>
<p>HybridWebViewClient重写shouldOverrideUrlLoading方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldOverrideUrlLoading</span><span class="params">(WebView view, String url)</span> </span>&#123;Uri parse = Uri.parse(url);</span><br><span class="line">       String path = parse.getPath();witch (path) &#123;</span><br><span class="line">           <span class="comment">//TODO</span> </span><br><span class="line">       &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>js那边发起请求协议。</p>
</li>
</ol>
<h2 id="方案分析"><a href="#方案分析" class="headerlink" title="方案分析"></a>方案分析</h2><p>这三种方案单独使用都比较有局限性。</p>
<ul>
<li><p>方案一的思路是native提前给h5实现好h5需要使用的方法，方法调用完全由h5控制，缺陷是h5调用的功能实现都由native实现，当h5页面中需要新功能的时候需要修改native才能支持。</p>
</li>
<li><p>方案二的思路是js提前给native提供方法，方法调用完全由native控制，缺陷是当js提供了新的方法那么需要修改native主动调用才能使用新功能。</p>
</li>
<li><p>方案三的思路是native拦截h5发过了的请求进行分发控制，js需要使用的功能是native已经提前准备好的，使用不同的url进行分发来使用，缺陷是h5使用新的功能那么需要修改native提供新功能。</p>
</li>
</ul>
<p>单独使用这三种方案的共同缺点就是js和native都是一个单向的调用，相互太过依赖。要是三种方案都用上是不是可以解决问题呢，其实根本问题不在这里，而在于这些方案都没有办法动态扩展，也就是说native一旦完成之后那么单纯靠js是很难完成功能扩展的。我们需要一种可以适应一定程度动态扩展的方案，那就让h5作为项目主导，native提供服务。 </p>
<h3 id="hybrid设计"><a href="#hybrid设计" class="headerlink" title="hybrid设计"></a>hybrid设计</h3><p>总体设计思路是h5控制整个业务流程以及交互流程。h5那边负责发命令并且回调，native负责响应命令。我是采用方案三来实现，客户端需要做的就是预先处理好这些命令（url）。既然是响应命令那么首先就需要把和业务无关的命令给整理出来，比较通用的包括下面内容（不一定全）：</p>
<ul>
<li>header控制。</li>
</ul>
<p>heade的样式可以参考新闻类app的详情页（这里不截图），包括内容：左边按钮（多个），右边按钮（多个），主标题，副标题。</p>
<p>需要做的控制是左、右按钮是否显示、显示的文本及图标以及点击按钮的回调，主、副标题是否显示及显示内容。</p>
<ul>
<li>页面刷新。</li>
</ul>
<p>页面刷新用于内容改变之后h5主动通知native进行刷新。</p>
<ul>
<li>页面跳转。</li>
</ul>
<p>页面跳转分成两种一种是页面跳转到一个新的native页面，另一种是在webview内部做跳转。native的跳转包括内容：跳转动画、跳转目标页、目标页需要的参数。</p>
<ul>
<li>loadingview/progressbar。</li>
</ul>
<p>通常情况建议直接使用h5的进度显示。loadingview的控制包括：loadingview是否显示，loadingview的显示样式（通常只有一种样式）。</p>
<ul>
<li>传感器数据。</li>
</ul>
<p>传感器这部分不一定每个应用都需要。比如某些h5页面需要做活动，那么里面可能会用的摇一摇这样的功能。传感器的控制包括：地理位置、方向、震动、运动量。</p>
<ul>
<li>h5离线包更新。</li>
</ul>
<p>离线包的更新对于h5来说是一条更新命令。不过在native实现上面需要包括：离线包更新检查（版本比较）、离线包下载、离线包解压保存。</p>
<ul>
<li>离线包开关。</li>
</ul>
<p>是否使用离线数据。native需要做的是开启离线包命令之后需要把请求的url映射到本地文件缓存。</p>
<ul>
<li>数据请求。</li>
</ul>
<p>数据请求是指h5需要请求数据不通过直接网络访问，而是通过native自己的网络服务获取数据，尤其是在跨域的情况下很方便。</p>
<h1 id="iOS上面"><a href="#iOS上面" class="headerlink" title="iOS上面"></a>iOS上面</h1><p>同样的，iOS也具备上述三个方案，分别是</p>
<ul>
<li>JavaScriptCore</li>
<li>WebviewLoad</li>
<li>Url Schema</li>
</ul>
<h2 id="JavaScriptCore"><a href="#JavaScriptCore" class="headerlink" title="JavaScriptCore"></a>JavaScriptCore</h2><p>在ios7后，Apple新增了一个JavaScriptCore让Native可以与H5更好的交互（Android早就有了），我们这里主要讨论js如何与Native通信，这里举一个简单的例子：<br>① 首先定义一个js方法，这里注意其中调用了一个没有声明的方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printHello</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//未声明方法</span></span><br><span class="line">    print(<span class="string">&quot;Hello, World!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后，上述未声明方法事实上是Native注入给window对象的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">NSString * scriptPath &#x3D; [[NSBundle mainBundle] pathForResource:@&quot;hello&quot; ofType:@&quot;js&quot;];</span><br><span class="line">NSString * scriptString &#x3D; [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];</span><br><span class="line"></span><br><span class="line">JSContext *context &#x3D; [[JSContext alloc] init];</span><br><span class="line">[context evaluateScript:scriptString];</span><br><span class="line"></span><br><span class="line">self.context[@&quot;print&quot;] &#x3D; ^(NSString *text) &#123;</span><br><span class="line">    NSLog(@&quot;%@&quot;, text&quot;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">JSValue *function &#x3D; self.context[@&quot;printHello&quot;];</span><br><span class="line">[function callWithArguments:@[]];</span><br></pre></td></tr></table></figure>
<p>这个样子，JavaScript就可以调用Native的方法了，这里Native需要注意方法注入的时机，一般是一旦载入页面便需要载入变量</p>
<ul>
<li>此方案需要特别注意的就是注入时机，要保证JS能调用到注入的方法</li>
</ul>
<h2 id="WebviewLoad"><a href="#WebviewLoad" class="headerlink" title="WebviewLoad"></a>WebviewLoad</h2><p>此方案和安卓一样</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[self.wkWebView loadHTMLString:@&quot;javascriptStr&quot; baseURL:@&quot;urlstr&quot;];</span><br></pre></td></tr></table></figure>

<h2 id="Url-Schema"><a href="#Url-Schema" class="headerlink" title="Url Schema"></a>Url Schema</h2><p>H5与Native交互的桥梁为Webview，而“联系”的方式是以url schema的方式做的，在用户安装app后，app可以自定义url schema，并且把自定义的url注册在调度中心， 例如</p>
<ul>
<li>dongfangdi://open 打开懂房帝App</li>
<li>weixin:// 打开微信</li>
</ul>
<p>事实上Native能捕捉webview发出的一切请求，所以就算这里不是这种协议，Native也能捕捉，这个协议的意义在于可以在浏览器中直接打开APP，<br>我们在H5获取Native方法时一般是会构造一个这样的请求，使用iframe发出（设置location会有多次请求覆盖的问题）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">requestHybrid(&#123;</span><br><span class="line">  <span class="comment">//创建一个新的webview对话框窗口</span></span><br><span class="line">  tagname: <span class="string">&#x27;dongfangdiApi&#x27;</span>,</span><br><span class="line">  <span class="comment">//请求参数，会被Native使用</span></span><br><span class="line">  param: &#123;&#125;,</span><br><span class="line">  <span class="comment">//Native处理成功后回调前端的方法</span></span><br><span class="line">  callback: <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//=====&gt;</span></span><br><span class="line">dongfangdi:<span class="comment">//dongfangdi?callback=dongfangdiAction&amp;param=%7B%22data1%22%3A1%2C%22data2%22%3A2%7D</span></span><br></pre></td></tr></table></figure>

<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>由于一开始我就强调过，不要完全依赖Hybrid来做app主要框架，它只是为我们提供更多的页面热更新，页面获取Native信息的一种技术。</p>
<ul>
<li>在iOS8.0以后，WebKit框架又给我们提供了一套方案</li>
<li>在WKUserContentController类中,我们可以看到这个方法<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;*! @abstract Adds a script message handler.</span><br><span class="line"> @param scriptMessageHandler The message handler to add.</span><br><span class="line"> @param name The name of the message handler.</span><br><span class="line"> @discussion Adding a scriptMessageHandler adds a function</span><br><span class="line"> window.webkit.messageHandlers.&lt;name&gt;.postMessage(&lt;messageBody&gt;) for all</span><br><span class="line"> frames.</span><br><span class="line"> *&#x2F;</span><br><span class="line">- (void)addScriptMessageHandler:(id &lt;WKScriptMessageHandler&gt;)scriptMessageHandler name:(NSString *)name;</span><br></pre></td></tr></table></figure>
然后我们可以在下面这个方法中处理对应的name<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message&#123;&#125;</span><br></pre></td></tr></table></figure>
强烈推荐此方法！！！</li>
</ul>
<p>相关demo代码已放在github上</p>
<ul>
<li><span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZy9IeWJyaWRfSW50ZXJhY3Rpb24=">https://github.com/Jack-Ving/Hybrid_Interaction<i class="fa fa-external-link-alt"></i></span>  这个是用Vue写的对应的js代码</li>
<li><span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZy9IeWJyaWQ=">https://github.com/Jack-Ving/Hybrid<i class="fa fa-external-link-alt"></i></span>  这个是采用拦截的方式写的OC代码</li>
</ul>
<p>由于仓促，如果遇到什么问题，尽管联系我.</p>
<blockquote>
<p>QQ:727881945  微信:Q727881945</p>
</blockquote>

    </div>

    
    
    
        <div class="reward-container">
  <div>希望对您有所帮助，您的支持将是我莫大的动力！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/wechatpay.png" alt="Jack Wang 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/alipay.png" alt="Jack Wang 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blogwebpage/tags/Hybrid/" rel="tag"># Hybrid</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blogwebpage/linux/home.html" rel="prev" title="Linux">
      <i class="fa fa-chevron-left"></i> Linux
    </a></div>
      <div class="post-nav-item">
    <a href="/blogwebpage/iOS/network/index.html" rel="next" title="网络">
      网络 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Hybrid"><span class="nav-number">1.</span> <span class="nav-text">Hybrid</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9C%A8%E5%AE%89%E5%8D%93%E4%B8%8A%E9%9D%A2"><span class="nav-number">1.1.</span> <span class="nav-text">在安卓上面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Native%E6%8F%90%E4%BE%9B%E6%96%B9%E6%B3%95%EF%BC%8Cjs%E8%B0%83%E7%94%A8Native%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">Native提供方法，js调用Native方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Native%E5%9C%A8%E6%9C%AC%E5%9C%B0%E6%B3%A8%E5%85%A5js%E6%96%B9%E6%B3%95%E5%B9%B6%E4%B8%94%E8%B0%83%E7%94%A8"><span class="nav-number">1.3.</span> <span class="nav-text">Native在本地注入js方法并且调用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Webview%E6%8B%A6%E6%88%AAAjax%E8%AF%B7%E6%B1%82%EF%BC%8C%E5%B9%B6%E5%81%9A%E4%B8%9A%E5%8A%A1%E5%A4%84%E7%90%86"><span class="nav-number">1.4.</span> <span class="nav-text">Webview拦截Ajax请求，并做业务处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%B9%E6%A1%88%E5%88%86%E6%9E%90"><span class="nav-number">1.5.</span> <span class="nav-text">方案分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#hybrid%E8%AE%BE%E8%AE%A1"><span class="nav-number">1.5.1.</span> <span class="nav-text">hybrid设计</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#iOS%E4%B8%8A%E9%9D%A2"><span class="nav-number">2.</span> <span class="nav-text">iOS上面</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScriptCore"><span class="nav-number">2.1.</span> <span class="nav-text">JavaScriptCore</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WebviewLoad"><span class="nav-number">2.2.</span> <span class="nav-text">WebviewLoad</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Url-Schema"><span class="nav-number">2.3.</span> <span class="nav-text">Url Schema</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jack Wang"
      src="/blogwebpage/images/avatar.gif">
  <p class="site-author-name" itemprop="name">Jack Wang</p>
  <div class="site-description" itemprop="description">书山有路勤为径，学海无涯苦作舟！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blogwebpage/archives/">
        
          <span class="site-state-item-count">52</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blogwebpage/categories/">
          
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blogwebpage/tags/">
          
        <span class="site-state-item-count">54</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Jack-Ving"><i class="github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjcyNzg4MTk0NUBxcS5jb20=" title="E-Mail → mailto:727881945@qq.com"><i class="envelope fa-fw"></i>E-Mail</span>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><span class="exturl" data-url="aHR0cHM6Ly9iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备16036665号-2 </span>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jack Wang</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        


  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1277804316&web_id=1277804316"></script>
  </div>






      </div>
    </footer>
  </div>

  
  <script src="/blogwebpage/lib/anime.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.ui.min.js"></script>

<script src="/blogwebpage/js/utils.js"></script>

<script src="/blogwebpage/js/motion.js"></script>


<script src="/blogwebpage/js/schemes/pisces.js"></script>


<script src="/blogwebpage/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/blogwebpage/js/local-search.js"></script>













  

  

</body>
</html>
